/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package imat;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import javax.swing.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import se.chalmers.ait.dat215.project.CreditCard;
import se.chalmers.ait.dat215.project.Customer;
import se.chalmers.ait.dat215.project.IMatDataHandler;
import se.chalmers.ait.dat215.project.Order;
import se.chalmers.ait.dat215.project.Product;
import se.chalmers.ait.dat215.project.ProductCategory;
import se.chalmers.ait.dat215.project.ShoppingCart;
import se.chalmers.ait.dat215.project.ShoppingItem;

/**
 *
 * @author Andreas
 */
public class DataHandler {

    private static DataHandler instance = null;
    private IMatDataHandler iMatDataHandler;
    private List<Category> categories = new LinkedList<Category>();
    private IMatView mainWindow;
    private Map<String,ShoppingCart> savedCarts = new HashMap<String,ShoppingCart>();

    private Timer timer;
    protected SubMenuItem lastClicked = null;

    public String mark;
    public String category;
    public String categoryLabel;


    protected DataHandler() {}

    public static DataHandler getInstance() {
        if (instance == null) {
            instance = new DataHandler();
            instance.init();
        }
        return instance;
    }

    public void init() {
        iMatDataHandler = IMatDataHandler.getInstance();

        timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                mainWindow.getFavoriteMenuButton().setForeground(Color.BLACK);
                timer.stop();
            }
        });

        loadCategories();
        loadCartsFromFile();
    }

    public void loadCategories() {
        Scanner sc = null;
        try {
            sc = new Scanner(new File("categories.txt"));
            System.out.println("--- Read categories.txt ---");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (sc != null) {
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                Scanner lineScanner = new Scanner(line).useDelimiter(";");
                List<Product> l = new LinkedList<Product>();
                CategoryName tc = CategoryName.valueOf(lineScanner.next());
                CategoryName c = CategoryName.valueOf(lineScanner.next());
                String handler = lineScanner.next();
                while (lineScanner.hasNext()) {
                    l.add(iMatDataHandler.getProduct(lineScanner.nextInt()));
                }
                if (l.isEmpty()) {
                    ProductCategory pc = ProductCategory.valueOf(c.toString());
                    for (Product p : iMatDataHandler.getProducts(pc)) {
                        l.add(p);
                    }
                }
                categories.add(new Category(tc, l, c, handler));
                System.out.println("Add category " + handler);
            }
            System.out.println("--- EOF ---");
        }

    }

    public SubMenuItem getLastClicked() {
        return lastClicked;
    }

    public void setLastClicked(SubMenuItem lastClicked) {
        this.lastClicked = lastClicked;
    }

    

    public void setMainWindow(IMatView i) {
        mainWindow = i;
    }

    public IMatView getMainWindow () {
        return mainWindow;
    }

    public Product getProduct(int idNbr) {
        return iMatDataHandler.getProduct(idNbr);
    }

    public ImageIcon getImageIcon(Product p, Dimension d) {
        return getImageIcon(p, d.width, d.height);
    }

    public ImageIcon getImageIcon(Product p, int width, int height) {
        return iMatDataHandler.getImageIcon(p, width, height);
    }

    public void addToShoppingCart(Product p, double amount) {
        ShoppingCart shoppingCart = iMatDataHandler.getShoppingCart();
        
        boolean found = false;
        for (ShoppingItem i : shoppingCart.getItems()) {
            if (p.getProductId() == i.getProduct().getProductId()) {
                found = true;
                i.setAmount(i.getAmount()+amount);
                shoppingCart.fireShoppingCartChanged();
                break;
            }
        }
        if (found == false) {
            shoppingCart.addProduct(p, amount);
        }

        System.out.println("Buying: " + p.getName());
    }

    public void addToShoppingCart(Product p) {
        addToShoppingCart(p, 1);
    }

    public void addToShoppingCart(ShoppingItem item) {
        addToShoppingCart(item.getProduct(), item.getAmount());
    }

    public Customer getCustomer() {
        return iMatDataHandler.getCustomer();
    }

    public ShoppingCart getShoppingCart() {
        return iMatDataHandler.getShoppingCart();
    }

    public void placeOrder() {

      iMatDataHandler.placeOrder();

    }

    public int getNumberOfOrders() {

        return iMatDataHandler.getOrders().size();

    }

    public Category getCategory(CategoryName category) {
        for (Category c : categories) {
            if (c.equals(category)) {
                return c;
            }
        }
        return null;
    }

    public List<Category> getCategoriesFromTop(String topCategory) {
        List<Category> list = new LinkedList<Category>();
        System.out.print(topCategory + " contains.. ");
        CategoryName tc = CategoryName.valueOf(topCategory);
        for (Category c : categories) {
            if (c.hasTopCategory(tc)) {
                list.add(c);
                System.out.print(c.getHandler()+" ");
            }
        }
        System.out.println();
        return list;
    }

    public java.util.List<Product> favorites() {
        return iMatDataHandler.favorites();
    }

    public void addFavorite(Product product) {
        iMatDataHandler.addFavorite(product);

        mainWindow.getFavoriteMenuButton().setForeground(Color.GREEN);
        System.out.println("addFavorite");

        // Start timer
        timer.start();
    }

    public void removeFavorite(Product product) {
        iMatDataHandler.removeFavorite(product);
        mainWindow.getFavoritesView().updateFavorites();

        //mainWindow.getFavoriteMenuButton().setForeground(Color.GREEN);
        System.out.println("removeFavorite");

        // Start timer
        //timer.start();
    }

    public boolean isFavorite(Product product) {
        return iMatDataHandler.isFavorite(product);
    }

    public CreditCard getCreditCard() {
        return iMatDataHandler.getCreditCard();
    }

    public Map<String,ShoppingCart> getSavedCarts() {
        System.out.println(savedCarts.size());
        return savedCarts;
    }

    public void saveCart(ShoppingCart cart, String name) {
        savedCarts.put(name, new SavedShoppingCart(cart));
        mainWindow.getSavedTrolleysButton().doClick();
    }

    public void removeCart(String name) {
        savedCarts.remove(name);
        mainWindow.getSavedTrolleysButton().doClick();
    }

    public List<Product> findProducts(String str) {
        return iMatDataHandler.findProducts(str);
    }

    public void addSavedCartToTrolley(ShoppingCart cart) {
        for (ShoppingItem item : cart.getItems()) {
            
            addToShoppingCart(item);
        }
    }

    public void addOrderToTrolley(Order order) {
        for (ShoppingItem item : order.getItems()) {

            addToShoppingCart(item);
        }
    }

    public java.util.List<Order> getOrders() {
        return iMatDataHandler.getOrders();
    }

    public void shutDown() {
        saveCartsToFile();

        iMatDataHandler.shutDown();
    }

    public void saveCartsToFile() {
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new File("savedCarts.txt"));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

        Set<Entry<String,ShoppingCart>> cartSets = savedCarts.entrySet();
        for (Entry<String,ShoppingCart> cart : cartSets) {
            ShoppingCart sc = cart.getValue();
            pw.append(cart.getKey()+";");
            for (ShoppingItem item : sc.getItems()) {
                pw.append(item.getProduct().getProductId()+";"+item.getAmount()+";");
            }
            pw.append("\n");
        }
        pw.close();
    }

    public void loadCartsFromFile() {
        Scanner scanner = null;
        try {
            scanner = new Scanner(new File("savedCarts.txt"));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DataHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

        String line;
        while (scanner.hasNextLine()) {
            ShoppingCart cart = new SavedShoppingCart();
            line = scanner.nextLine();
            Scanner lineScanner = new Scanner(line).useDelimiter(";");
            lineScanner.useLocale(Locale.ENGLISH);
            String name = lineScanner.next();
            while (lineScanner.hasNext()) {
                int id = lineScanner.nextInt();
                double amount = lineScanner.nextDouble();
                cart.addProduct(getProduct(id), amount);
            }
            savedCarts.put(name, cart);
        }
    }

    public void showSideTrolley() {
        mainWindow.sideTrolley.showSideTrolley();
    }

    public void hideSideTrolley() {
        mainWindow.sideTrolley.hideSideTrolley();
    }

    public boolean isCustomerComplete() {
        return iMatDataHandler.isCustomerComplete();
    }
}
